package com.lxj.sso.util;

import com.alibaba.fastjson.JSONObject;
import com.lxj.sso.config.LxjConfig;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @ClassName HttpClientUtils
 * @Description TODO
 * @Author wenqing_liu
 * @Date 2020/11/30 13:56
 */
public class HttpClientUtils {

    private final LxjConfig lxjConfig;

    private static final String CONTENT_TYPE = "Content-Type";
    private static final String APPLICATION = "application/json";

    public HttpClientUtils(LxjConfig lxjConfig) {
        this.lxjConfig = lxjConfig;
    }

    public String test() {
        return lxjConfig.getAppId();
    }

    /**
     * 获取appToken
     * @return  appToken
     */
    public String getAppToken() {

        String appTokenUrl = lxjConfig.getAppTokenUrl();

        JSONObject jsonObject = getAppTokenJsonObject();

        String appToken = "";
        try {
            JSONObject response = callHttpClientByPost(appTokenUrl, jsonObject);
            appToken = response.getString("app_token");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return appToken;
    }

    private JSONObject getAppTokenJsonObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId", lxjConfig.getAppId());
        jsonObject.put("appSecuret", lxjConfig.getAppSecuret());
        jsonObject.put("tenantid", lxjConfig.getTenantId());
        jsonObject.put("accountId", lxjConfig.getAccountId());
        jsonObject.put("language", lxjConfig.getLanguage());
        return jsonObject;
    }

    /**
     * 获取accessToken
     * @param appToken      appToken
     * @param phone         用户手机号
     * @return              accessToken
     * @throws IOException  异常
     */
    public JSONObject getAccessToken(String appToken, String phone) throws IOException {

        String loginUrl = lxjConfig.getLoginUrl();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", phone);
        jsonObject.put("apptoken", appToken);
        jsonObject.put("tenantid", lxjConfig.getTenantId());
        jsonObject.put("accountId", lxjConfig.getAccountId());
        jsonObject.put("usertype", lxjConfig.getUserType());

        return callHttpClientByPost(loginUrl, jsonObject);
    }

    /**
     * 以Post方式调用openApi接口，获取token
     *
     * @param url           url地址
     * @param request       请求参数
     * @return              返回参数
     */
    public JSONObject callHttpClientByPost(String url, JSONObject request) throws IOException {

        // 构造HttpClient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建 post 的请求
        HttpPost httpPost = new HttpPost(url);
        // 设置请求头
        httpPost.setHeader(CONTENT_TYPE, APPLICATION);
        // 设置请求体
        StringEntity stringEntity = new StringEntity(request.toJSONString(), "utf-8");
        httpPost.setEntity(stringEntity);

        return getTokenResult(httpClient.execute(httpPost));
    }

    /**
     * 以 get 方式调用
     * @param url       调用地址
     * @return
     */
    public static String callHttpClientByGet(String url) {
        String result = "";

        HttpGet httpGet = new HttpGet(url);

        // 构造HttpClient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 响应模型; 由 Client 执行(发送) post 请求
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 从响应模型中获取响应体
            HttpEntity responseEntity = response.getEntity();
            result = EntityUtils.toString(responseEntity);
            StatusLine statusLine = response.getStatusLine();
            System.out.println("响应状态为：" + statusLine);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 获取JSONObject类型的响应体
     * 如果key： data 存在即获取到AccessToken
     *              不存在，获取报错的响应体
     * @param execute
     * @return
     */
    private JSONObject getTokenResult(CloseableHttpResponse execute) {
        JSONObject result = null;
        try {
            // 从响应模型中获取响应体
            HttpEntity responseEntity = execute.getEntity();
            String response = EntityUtils.toString(responseEntity);
            JSONObject responseObject = JSONObject.parseObject(response);
            result = (responseObject.getJSONObject("data") != null) ? responseObject.getJSONObject("data") : responseObject;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
